import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_yn_goods/config/app_routes.dart';
import 'package:flutter_yn_goods/config/app_translations.dart';
import 'package:flutter_yn_goods/pages/login/register/model_register.dart';
import 'package:flutter_yn_goods/user/app_user_manager.dart';
import 'package:flutter_yn_goods/utils/album_utils.dart';
import 'package:flutter_yn_goods/utils/http/http_export.dart';
import 'package:flutter_yn_goods/utils/loading/loading_utils.dart';
import 'package:flutter_yn_goods/utils/log/utils_log.dart';
import 'package:flutter_yn_goods/widgets/widget_picker_style.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class RegisterLogic extends GetxController {
  bool isAgency = Get.arguments?['isAgency'];

  var showPassword = false.obs;
  var showPasswordAgain = false.obs;
  var phoneErrorText = "".obs;
  var passwordErrorText = "".obs;
  var passwordAgainErrorText = "".obs;
  var lengthLimit = 32;
  var agreementRx = false.obs;

  // var passwordLengthLimit = 32;
  var canRegister = false.obs;

  // var agencyCodeEditController = TextEditingController();

  var nameEditController = TextEditingController();
  var phoneEditController = TextEditingController();

  // var agentPhoneEditController = TextEditingController();

  var agentIdEditController = TextEditingController();

  var passwordEditController = TextEditingController();
  var passwordAgainEditController = TextEditingController();
  var addressEditController = TextEditingController();
  var emailEditController = TextEditingController();

  Rx<ModelRegister> registerModelRx = Rx(ModelRegister());

  var addressRx = ''.obs;
  var cardIdEditController = TextEditingController();

  // 身份证相关变量
  var idCardFrontPath = ''.obs;
  var idCardFrontUploaded = false.obs;

  @override
  void onInit() {
    super.onInit();
    // 0912345678
    if (kDebugMode) {
      // 09123456781
      agentIdEditController.text = '110109';
      nameEditController.text = 'trần thị quỳnh';
      phoneEditController.text = '0332530013';
      passwordEditController.text = '1235234';
      passwordAgainEditController.text = '1235234';
      addressEditController.text = 't252 lạc Trung, Vĩnh Tuy';

      registerModelRx.value.phone = phoneEditController.text;
      registerModelRx.value.spread = agentIdEditController.text;
      registerModelRx.value.password = passwordEditController.text;
      registerModelRx.value.name = nameEditController.text;
      registerModelRx.value.address = addressEditController.text;
      // registerModelRx.value.agentPhone = agentPhoneEditController.text;
    }
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();

    nameEditController.dispose();
    phoneEditController.dispose();
    agentIdEditController.dispose();
    passwordEditController.dispose();
    passwordAgainEditController.dispose();
    addressEditController.dispose();
    emailEditController.dispose();
    // agencyCodeEditController.dispose();
    cardIdEditController.dispose();
  }

  // void onAccountTextChange() {
  //   var account = accountEditController.text;
  //   if (account.isEmpty) {
  //     accountErrorText.value = "";
  //   } else {
  //     if (account.length < 3) {
  //       accountErrorText.value = "账号至少3位";
  //     } else {
  //       accountErrorText.value = "";
  //       checkAccount(account);
  //     }
  //   }
  //   _checkButtonState();
  // }

  void onPasswordTextChange() {
    var password = passwordEditController.text;
    var password2 = passwordAgainEditController.text;
    if (password.isNotEmpty && password.length < 6) {
      passwordErrorText.value = LocaleKeys.password_min_length.tr;
    } else {
      passwordErrorText.value = "";
    }
    if (password2.isNotEmpty && password2 != password) {
      passwordAgainErrorText.value = LocaleKeys.password_not_match.tr;
    } else {
      passwordAgainErrorText.value = "";
    }
    checkButtonState();
  }

  void checkButtonState() {
    // var nameEditController = TextEditingController();
    // var phoneEditController = TextEditingController();
    // var agentPhoneEditController = TextEditingController();
    //
    // var passwordEditController = TextEditingController();
    // var passwordAgainEditController = TextEditingController();
    // var addressEditController = TextEditingController();
    // var emailEditController = TextEditingController();
    canRegister.value = nameEditController.text.trim().length > 1 &&
        phoneEditController.text.trim().length > 9 &&
        // (isAgency
        //     ? (agencyCodeEditController.text.trim().length > 4)
        //     : (agentPhoneEditController.text.trim().length > 9)) &&
        agentIdEditController.text.trim().length > 4 &&
        passwordEditController.text.trim().length > 5 &&
        (isAgency ? (idCardFrontUploaded.value) : true) &&
        (isAgency ? (cardIdEditController.text.trim().length > 10) : true) &&
        addressEditController.text.trim().length > 3 &&
        passwordEditController.text.trim() ==
            passwordAgainEditController.text.trim();
  }

  void changePasswordState() {
    showPassword.value = !showPassword.value;
  }

  void changePasswordAgainState() {
    showPasswordAgain.value = !showPasswordAgain.value;
  }

  // 选择并上传身份证正面照片
  void pickAndUploadIdCardFront() async {
    final asset = await AlbumUtils.pickSingleImage();
    if (asset == null) return;

    final file = await asset.file;
    if (file == null) return;

    final bytes = await file.readAsBytes();
    final fileName =
        "id_card_front_${DateTime.now().millisecondsSinceEpoch}.${file.path.split('.').last}";

    LoadingUtils.showLoading();

    final response = await HttpManager().upload(
        fileData: bytes,
        fileName: fileName,
        requestId: '110012',
        onSendProgress: (index, total) {
          clog('message    $index   $total');
        });

    LoadingUtils.dismiss();

    if (response.isSuccess && response.data != null) {
      idCardFrontPath.value = response.data['url'];
      idCardFrontUploaded.value = true;
      registerModelRx.update((val) {
        val?.idCardFront = idCardFrontPath.value;
      });
      checkButtonState();
    } else {
      LoadingUtils.showToast(LocaleKeys.upload_failed.tr);
    }
    // } catch (e) {
    //   LoadingUtils.dismiss();
    //   LoadingUtils.showToast(LocaleKeys.upload_failed.tr);
    // }
  }

  bool isValidVietnamId(String id) {
    final RegExp vietnamIdRegex = RegExp(r'^\d{9}$|^\d{12}$');
    return vietnamIdRegex.hasMatch(id);
  }

  void register() async {
    if (isAgency &&
        isValidVietnamPhoneNumber(cardIdEditController.text) == false) {
      LoadingUtils.showToast(LocaleKeys.please_enter_id_card.tr);
      return;
    }

    // if (kDebugMode) {
    //   if (!isValidVietnamPhoneNumber(phoneEditController.text.trim())) {
    //     LoadingUtils.showToast('请输入正确的电话号码');
    //     return;
    //   }
    //   if (!isValidVietnamPhoneNumber(agentPhoneEditController.text.trim())) {
    //     LoadingUtils.showToast('请输入正确的代理商电话号码');
    //     return;
    //   }
    // }
    if (agreementRx.value == false) {
      LoadingUtils.showToast(LocaleKeys.please_agree_terms.tr);
      return;
    }
    var response = await HttpManager().post(
        isAgency ? API.registerAgency : API.register1,
        params: registerModelRx.value.toJson(),
        uiType: HttpUIType.loadingAndToast);

    if (response.isSuccess) {
      var response = await AppUserManager().login(
          phoneEditController.text, passwordEditController.text,
          isAgency: isAgency);

      if (response.isSuccess) {
        // Get.get(AppRoutes.main);
        Get.back();
        Get.back();
      } else {
        LoadingUtils.showToast(
            "${LocaleKeys.login_failed.tr}${response.message}");
      }
    } else {
      LoadingUtils.dismiss();
      LoadingUtils.showToast(
          "${LocaleKeys.register_failed.tr}${response.message}");
    }
  }

  showAgePicker({int? initAge}) async {
    // 生成年龄范围：16-80
    final ages = List.generate(80 - 16 + 1, (index) => (index + 16).toString());
    // 计算默认选中位置
    int initIndex = initAge ?? 0;
    clog('initAge   $initIndex');
    Pickers.showSinglePicker(
      Get.context!,
      data: ages,
      selectData: initIndex.toString(),
      pickerStyle: WidgetPickerStyle.createPickerStyle(),
      onConfirm: (var selected, int data) {
        registerModelRx.update((fn) {
          fn?.age = (data + 16).toString();
        });
        // return int.parse(ages[selected[0]]);
      },
    );
  }

  bool isValidVietnamPhoneNumber(String input) {
    final regex = RegExp(r'^(?:\+84|0)(3|5|7|8|9)\d{8}$');
    return regex.hasMatch(input);
  }
}
